package com.kreig133.analytic.extractors;

import com.kreig133.analytic.interfaces.DataMiner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author C.C.-fag
 */
public class Parser implements DataMiner {

    Pattern dataPattern = Pattern.compile("\\d+[\\s&&[^\\n]]+(\\d+)[\\s&&[^\\n]]+\\d+\\s*");
    Pattern timePattern = Pattern.compile("STEP:\\s*(\\d+)\\s*=\\s*(\\d+)ms\\s");
    File file;

    public Parser() {
    }

    public Parser(String pattern) {
        this(null, pattern);
    }

    public Parser(File file) {
        this(file, null);
    }

    public Parser(File file, String pattern) {
        if (file != null) {
            this.file = file;
        }
        if (pattern != null) {
            this.dataPattern = Pattern.compile(pattern);
        }
    }

    public void setFile(File file) {
        this.file = file;
    }

    public Map<Double, Double> getProcessedData() {
        Map result = new HashMap<Double, Double>();
        if (file == null ? true : (!(file.exists()))) {
            System.out.println(file);
            throw new RuntimeException();
        }
        BufferedReader br = null;
        String data = null;
        try {
            br = new BufferedReader(new FileReader(file));
            data = br.readLine();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        ArrayList<Double> rawData = new ArrayList<Double>();
        boolean timeIsFound = false;
        double timeStep = 1;
        while (data != null) {
            if (!timeIsFound) {
                Matcher timeParser = timePattern.matcher(data);
                if (timeParser.find()) {
                    timeIsFound = true;
                    timeStep = Double.parseDouble(timeParser.group(2))
                            / Double.parseDouble(timeParser.group(1));
                }
            }

            Matcher dataParser = dataPattern.matcher(data);

            if (dataParser.find()) {
                rawData.add(Double.parseDouble(dataParser.group(1)));
//                System.out.println(dataParser.group(1));
            }
            try {
                data = br.readLine();
            } catch (IOException ex) {
                ex.printStackTrace();
                System.err.println(95);
            }
        }

        for (int i = 0; i < rawData.size(); i++) {
            result.put(i * timeStep, rawData.get(i));
        }

        return result;
    }
}
